package org.hxzon.tapestry5.util;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.net.URLCodec;
import org.apache.tapestry5.services.URLEncoder;

public class Base64UrlEncoderImpl implements URLEncoder {

    //hxzon:use this encoder,you must set tomcat.server.xml's get encoding
    //<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" 
    //URIEncoding="UTF-8"/>
    private URLCodec delegate = new URLCodec();

    @Override
    public String encode(String input) {
        try {
            if (Base64.isBase64(input)) {
                return input;
            }
            return delegate.encode(input);
        } catch (EncoderException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String decode(String input) {
        try {
            if (Base64.isBase64(input)) {
                return delegate.decode(input);
            }
            return input;
        } catch (DecoderException e) {
            throw new RuntimeException(e);
        }
    }

}
